package whf.framework.web.listener;

import java.util.Set;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.acegisecurity.context.HttpSessionContextIntegrationFilter;
import org.acegisecurity.context.SecurityContextHolder;

import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.security.UserContext;
import whf.framework.security.acegiimp.UserDetailsImp;
import whf.framework.security.entity.Role;
import whf.framework.security.entity.User;
import whf.framework.util.StringUtils;
import whf.framework.web.WebContextHolder;

/**
 * @author wanghaifeng
 * @create Aug 13, 2006 10:40:08 PM
 * 
 */
public class AcegiSecuritySessionListener implements
		HttpSessionAttributeListener, HttpSessionListener {

	private static Log log = LogFactory.getLog(AcegiSecuritySessionListener.class);
	
	public void sessionCreated(HttpSessionEvent event) {
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		
	}

	public void attributeAdded(HttpSessionBindingEvent event) {
		log.debug(event.getName());
		try{
			if(StringUtils.equals(event.getName(), HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY)){
				org.acegisecurity.context.SecurityContext sc = SecurityContextHolder.getContext();
				UserDetailsImp userDetails = (UserDetailsImp)sc.getAuthentication().getPrincipal();
				User user = userDetails.getUser();
				Set<Role> roles = userDetails.getRoles();
				UserContext uc = WebContextHolder.getWebContext().getUserContext();
				uc.upgradeToUser(WebContextHolder.getWebContext().getRequest().getUserPrincipal(), user, roles);
			}
		}catch(Exception e){
			log.error(this, e);
		}
	}

	public void attributeRemoved(HttpSessionBindingEvent event) {
		
	}

	public void attributeReplaced(HttpSessionBindingEvent event) {
		
	}

}
